from django.contrib.auth import logout
from django.shortcuts import render, redirect
from django.urls import reverse_lazy

from django.views.generic import TemplateView, FormView, CreateView

from .forms import (LoginForm, UserRegisterForm)


class user_login_view_class(FormView):
    """用户登录视图"""
    form_class = LoginForm
    template_name = 'user_account/login.html'
    success_url = reverse_lazy("index")

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs


class user_register_view_class(CreateView):
    """用户注册视图"""
    form_class = UserRegisterForm
    template_name = 'user_account/user_register.html'
    success_url = reverse_lazy("user_login")


def logout_fun(request):
    """ 用户退出函数 """

    url = reverse_lazy("user_login")
    if not request.user.is_authenticated:
        return redirect(url)

    logout(request)
    return redirect(url)
